//package projects.part5;

import info.gridworld.grid.AbstractGrid;
import info.gridworld.grid.Location;

import java.util.ArrayList;
import java.util.HashMap;

public class SparseBoundedGrid2a<E> extends AbstractGrid<E> {

    private HashMap<Location,E> occMap;
    private int numCols;
    private int numRows;

    public SparseBoundedGrid2a(int rows, int cols){
        if (rows <= 0) {
            throw new IllegalArgumentException("Error! Rows <= 0");
        }
        if (cols <= 0) {
            throw new IllegalArgumentException("Error! Cols <= 0");
        }
        numRows = rows;
        numCols = cols;
        occMap = new HashMap<Location,E>();
    }

    @Override
    public int getNumRows() {
        return numRows;
    }

    @Override
    public int getNumCols() {
        return numCols;
    }

    @Override
    public boolean isValid(Location loc) {
        int c = loc.getCol();
        int r = loc.getRow();
        return 0 <= c && c < numCols && 0 <= r && r < numRows;
    }

    @Override
    public E put(Location loc, E obj) {
        if (!isValid(loc))
            throw new IllegalArgumentException("Location " + loc
                    + " is not valid");
        if (obj == null)
            throw new NullPointerException("obj == null");

        E old = remove(loc);

        occMap.put(loc,obj);

        return old;
    }

    @Override
    public E remove(Location loc) {
        if (!isValid(loc)) {
            throw new IllegalArgumentException("Error! Location: " + loc + " is InValid.");
        }

        E obj = null;
        if (get(loc)!=null)
            obj = occMap.remove(loc);
        return obj;
    }

    @Override
    public E get(Location loc) {
        if(occMap.containsKey(loc))
            return occMap.get(loc);
        return null;
    }

    @Override
    public ArrayList<Location> getOccupiedLocations() {
        ArrayList<Location> res = new ArrayList<Location>();
        for (Location loc : occMap.keySet())
            res.add(loc);
        return res;
    }
}
